const wx_server_sdk = require('wx-server-sdk');

wx_server_sdk.init({
    env: 'direshui-6gl2m2r1275bd635'
});
const db = wx_server_sdk.database();
const dbCommand = db.command;


async function funcMain(e) {
    console.log('云函数收到的数据', e)

    var demoData = {
        devicename: 'liuzhuangHuiguan',

        payload:

        {
            data: {
                leftAccuFlow: 0,
                nowFlow: 59.9,
                rightAccuFlow: 2345
            }
        },

        productid: 'VLH0GQHFDO',

        seq: 11683726,

        timestamp: 1600582889,

        topic: 'VLH0GQHFDO/liuzhuangHuiguan/event'
    }


    var theData = {
        wellName: e.devicename == 'liuzhuangHuiguan' ? '刘庄回灌井' : '刘庄开采井',
        // wellType:

        ts: e.timestamp,
        time: tsToDateStr(e.timestamp),

        rightAccuFlow: e.payload.data.rightAccuFlow,
        leftAccuFlow: e.payload.data.leftAccuFlow,

        nowFlow: e.payload.data.nowFlow,
    }

    if (theData.wellName.indexOf('开采井') > -1) {
        theData.wellType = '开采井';
    } else {
        theData.wellType = '回灌井';
    }

    // console.log('整理后的数据格式', theData)


    var saveDataToDb = await db.collection('nowData').add({
        data: theData
    })

    console.log('存到数据库的结果:', saveDataToDb);




    return null;
}


function getNowTimestamp() {
    return new Date().getTime();
}

function getBeijingTime(localTs) {
    var time_ts = localTs;
    if (typeof(localTs) != 'number' || localTs == 0) {
        time_ts = getNowTimestamp();
    }

    var time = tsToDateStr(time_ts);

    return {
        ts: time_ts,
        time,
    };
}

function tsToDateStr(ts_para) {
    //2020-06-14 20:49:59
    //未在此弥补时差
    var time_ts = new Date(ts_para * 1000 + 8 * 3600000);

    // console.log('用于制作中文的ts', time_ts.getTime());

    var time_str = time_ts.getFullYear() + '-';

    if ((time_ts.getMonth() + 1) < 10) {
        time_str += '0';
    }
    time_str += '' + (time_ts.getMonth() + 1) + '-';


    if (time_ts.getDate() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getDate() + ' ';


    if (time_ts.getHours() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getHours() + ':';

    if (time_ts.getMinutes() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getMinutes() + ':';

    if (time_ts.getSeconds() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getSeconds(); // + ':' + time_ts.getMilliseconds();

    return time_str;
}


exports.main = funcMain